/*
 *海洋气象功能模块
 */
define("func/oceanWeather", [
    "leaflet",
    "plugins/papaparse",
    "func/base",
    "leaflet/weatherLayer",
    "data/ajax"

], function(L, Papa) {

    L.ICT.Func.add("OceanWeather", {

        Class: L.Class.extend({

            initialize: function() {
                this.menu = L.ict.app.menu;
                this.menuid = 'ict_menu_main_hyqx';
                this.ictmap = L.ict.app.ictmap;
                this.ajax = new L.ICT.Ajax();
                this.config = Project_ParamConfig.oceanWeatherConfig;
                this._container = null;
                this._popPanel = null;
            },

            start: function() {
                if (this._popPanel || this._container) {
                    return;
                }
                this._initUi();
                this._initEvts();
                this.menu.mainmenu.deactiveMenuExceptOne(this.menuid);
                this.menu.mainmenu.disableMenuExceptOne(this.menuid);
                this.menu.mainmenu.deactivePortInfo(); //退出港口菜单
                this.ictmap.OperateState.weather = true;
            },

            stop: function() {
                if (this._popPanel) {
                    this._popPanel.remove();
                }
                this.removeWeather();
                this.removePressure();
                this.remove500mb();
                this.removeWind();
                this.removeWave();
                this.removeSurge();
                this.removeFlow();
                this.removeTemperature();
                this.removeVisibility();
                this.menu.mainmenu.deactiveMenu(this.menuid);
                this.menu.mainmenu.enableMenu();
                this.ictmap.realtarget.addRealTargetLayer();
                this.ictmap.OperateState.weather = false;
            },

            _initUi: function() {
                var options = {
                    title: '海洋气象',
                    width: 120,
                    height: 320,
                    left: 100,
                    top: 140,
                    scroll: true
                };
                options.contentHTML = this._container = $(this.getContentHTML());
                var pop = this._popPanel = new L.ICT.PopPanel(options);
                pop.show();
                pop.on("popPanelRemove", function() {
                    this._popPanel = null;
                    this._container = null;
                    this.removeWeather();
                    this.removePressure();
                    this.remove500mb();
                    this.removeWind();
                    this.removeWave();
                    this.removeSurge();
                    this.removeFlow();
                    this.removeTemperature();
                    this.removeVisibility();
                    this.menu.mainmenu.deactiveMenu(this.menuid);
                    this.menu.mainmenu.enableMenu();
                    this.ictmap.realtarget.addRealTargetLayer();
                    this.ictmap.OperateState.weather = false;
                }, this);
            },

            getContentHTML: function() {
                var html = [];
                html.push('<div class="oceanweather_container">');
                // html.push('<p class="title">选择气象:</p>');
                html.push('<ul>');

                html.push('<li><label>海潮：</label>');
                html.push('<ul>');
                html.push('<li class="item item-wave" data-key="5"><label><input type="checkbox"/>&nbsp&nbsp浪</label></li>');
                html.push('<li class="item item-surge" data-key="6"><label><input type="checkbox"/>&nbsp&nbsp涌</label></li>');
                html.push('</ul>');
                html.push('</li>');

                html.push('<li><label>洋流：</label>');
                html.push('<ul>');
                html.push('<li class="item item-flow" data-key="7"><label><input type="checkbox"/>&nbsp&nbsp洋流</label></li>');
                html.push('</ul>');
                html.push('</li>');

                html.push('<li><label>水温：</label>');
                html.push('<ul>');
                html.push('<li class="item item-tep" data-key="8"><label><input type="checkbox"/>&nbsp&nbsp海温</label></li>');
                html.push('</ul>');
                html.push('</li>');

                html.push('<li><label>大气：</label>');
                html.push('<ul>');
                html.push('<li class="item item-weather" data-key="1"><label><input type="checkbox"/>&nbsp&nbsp天气</label></li>');
                html.push('<li class="item item-pressure" data-key="2"><label><input type="checkbox"/>&nbsp&nbsp气压</label></li>');
                html.push('<li class="item item-500mb" data-key="3"><label><input type="checkbox"/>&nbsp&nbsp500mb</label></li>');
                html.push('<li class="item item-wind" data-key="4"><label><input type="checkbox"/>&nbsp&nbsp风</label></li>');
                html.push('<li class="item item-visibility" data-key="9"><label><input type="checkbox"/>&nbsp&nbsp能见度</label></li>');
                html.push('</ul>');
                html.push('</li>');

                html.push('</ul>');
                html.push('</div>');
                return html.join('');
            },

            _initEvts: function() {
                if (!this._container) {
                    return;
                }
                var self = this;
                this._container.find('.item input[type=checkbox]').on('change', function(e) {
                    var type = +$(this).parent().parent().data('key');
                    var ischk = !!this.checked;
                    if (ischk && self.ictmap.realtarget.isRealTargetShow()) {
                        self.ictmap.realtarget.hideRealTargetLayer();
                    }
                    if (type === 1) {
                        ischk ? self.addWeather() : self.removeWeather();
                    } else if (type === 2) {
                        ischk ? self.addPressure('data/pressure.csv') : self.removePressure();
                    } else if (type === 3) {
                        ischk ? self.add500mb('data/500mb.csv') : self.remove500mb();
                    } else if (type === 4) {
                        ischk ? self.addWind('data/wind.csv') : self.removeWind();
                    } else if (type === 5) {
                        ischk ? self.addWave('data/wave.csv') : self.removeWave();
                    } else if (type === 6) {
                        ischk ? self.addSurge('data/surge.csv') : self.removeSurge();
                    } else if (type === 7) {
                        ischk ? self.addFlow('data/flow.csv') : self.removeFlow();
                    } else if (type === 8) {
                        ischk ? self.addTemperature('data/temperature.csv') : self.removeTemperature();
                    } else if (type === 9) {
                        ischk ? self.addVisibility('data/visibility.csv') : self.removeVisibility();
                    }
                });
            },

            getWeatherIcon: function(code) {
                return L.icon({
                    iconUrl: 'themes/images/weather/' + code + '.png',
                    iconSize: [24, 24]
                });
            },

            getWeatherName: function(code) {
                var name = code;
                switch (code) {
                    case 1:
                        name = '晴';
                        break;
                    case 2:
                        name = '阴';
                        break;
                    case 3:
                        name = '雨';
                        break;
                    default:
                        ;
                }
                return name;
            },

            getWeatherhtml: function(d1, d2) {
                var html = [];
                html.push('<div>');
                html.push('<table>');
                html.push('<tr><td>预报时效(小时)：</td><td>' + d1.hours + '</td></tr>');
                html.push('<tr><td>天气现象：</td><td>' + this.getWeatherName(d1.wea_code) + '</td></tr>');
                html.push('<tr><td>风向：</td><td>' + d1.wind_direction + '</td></tr>');
                html.push('<tr><td>风力(级)：</td><td>' + d1.wind_power + '</td></tr>');
                html.push('<tr><td>能见度(km)：</td><td>' + d1.visibility + '</td></tr>');
                html.push('</table>');
                html.push('<hr/>');
                html.push('<table>');
                html.push('<tr><td>预报时效(小时)：</td><td>' + d2.hours + '</td></tr>');
                html.push('<tr><td>天气现象：</td><td>' + this.getWeatherName(d2.wea_code) + '</td></tr>');
                html.push('<tr><td>风向：</td><td>' + d2.wind_direction + '</td></tr>');
                html.push('<tr><td>风力(级)：</td><td>' + d2.wind_power + '</td></tr>');
                html.push('<tr><td>能见度(km)：</td><td>' + d2.visibility + '</td></tr>');
                html.push('</table>');
                html.push('</div>');
                return html.join('');
            },

            addWeather: function() {
                var url = this.config.weatherUrl;
                this.removeWeather();
                this.weatherFeatureGroup = L.featureGroup([]).addTo(this.ictmap.map);
                this.ajax.get(url, null, true, this, function(res, error) {
                    if (error) {
                        return;
                    }
                    if (res.state !== 1) {
                        return;
                    }
                    var datas = res.msg.weathers;
                    for (var i = 0, len = datas.length; i < len; i += 2) {
                        var di = datas[i],
                            di1 = datas[i + 1];
                        var latlng = L.latLng(di.latitude, di.longitude);
                        var icon = this.getWeatherIcon(di.wea_code);
                        var marker = L.marker(latlng, { icon: icon });
                        marker.bindTooltip(this.getWeatherhtml(di, di1), {
                            direction: 'right'
                        });
                        if (this.ictmap.map.hasLayer(this.weatherFeatureGroup)) {
                            this.weatherFeatureGroup.addLayer(marker);
                        }
                    }
                });
            },

            removeWeather: function() {
                if (this.weatherFeatureGroup && this.ictmap.map.hasLayer(this.weatherFeatureGroup)) {
                    this.ictmap.map.removeLayer(this.weatherFeatureGroup);
                }
            },

            addPressure: function(url) {
                var self = this;
                var renderer = new L.TextCanvas();
                var options = {
                    renderer: renderer,
                    color: '#354656',
                    weight: 0.8,
                    opacity: 0.85,
                    fill: false
                };
                var arr = [];

                this.removePressure();
                this.pressureFeatureGroup = L.featureGroup([]).addTo(this.ictmap.map);

                Papa.parse(url, {
                    download: true,
                    complete: function(results) {},
                    step: function(results, parser) {
                        if (results.data[0][0] === '' && arr.length) {

                            // handler data -------------start------------------------
                            var latlngs = [];
                            for (var i = 0, len = arr.length; i < len; i++) {
                                var row = arr[i];
                                var lat = +row[0];
                                var lng = +row[1];
                                var value = options.text = +row[2];
                                var latlng = L.latLng(lat, lng);

                                if (i === 0) {
                                    latlngs.push(latlng);
                                } else {
                                    var lastlng = (latlngs[latlngs.length - 1]).lng;
                                    var extend = Math.abs(lng - lastlng);
                                    if (extend >= 180) { //解决经度范围超过180连线异常
                                        if (self.ictmap.map.hasLayer(self.pressureFeatureGroup)) {
                                            self.pressureFeatureGroup.addLayer(L.polyline(latlngs, options));
                                        }
                                        latlngs = [];
                                        latlngs.push(latlng);
                                    } else {
                                        latlngs.push(latlng);
                                        if (i === len - 1) {
                                            if (self.ictmap.map.hasLayer(self.pressureFeatureGroup)) {
                                                self.pressureFeatureGroup.addLayer(L.polyline(latlngs, options));
                                            }
                                            latlngs = [];
                                        }
                                    }
                                }
                            }
                            // handler datq ----------------end-----------------------------
                            arr = [];
                        } else {
                            if (arr) {
                                arr.push(results.data[0]);
                            } else {
                                arr = [];
                            }
                        }
                    }
                });
            },

            removePressure: function() {
                if (this.pressureFeatureGroup && this.ictmap.map.hasLayer(this.pressureFeatureGroup)) {
                    this.ictmap.map.removeLayer(this.pressureFeatureGroup);
                }
            },

            add500mb: function(url) {
                var self = this;
                var renderer = new L.TextCanvas();
                var options = {
                    renderer: renderer,
                    color: '#354656',
                    weight: 0.8,
                    opacity: 0.85,
                    fill: false
                };
                var arr = [];

                this.remove500mb();
                this.mb500FeatureGroup = L.featureGroup([]).addTo(this.ictmap.map);

                Papa.parse(url, {
                    download: true,
                    complete: function(results) {},
                    step: function(results, parser) {
                        if (results.data[0][0] === '' && arr.length) {

                            // handler data -------------start------------------------
                            var latlngs = [];
                            for (var i = 0, len = arr.length; i < len; i++) {
                                var row = arr[i];
                                var lat = +row[0];
                                var lng = +row[1];
                                var value = options.text = +row[2];
                                var latlng = L.latLng(lat, lng);

                                if (i === 0) {
                                    latlngs.push(latlng);
                                } else {
                                    var lastlng = (latlngs[latlngs.length - 1]).lng;
                                    var extend = Math.abs(lng - lastlng);
                                    if (extend >= 180) { //解决经度范围超过180连线异常
                                        if (self.ictmap.map.hasLayer(self.mb500FeatureGroup)) {
                                            self.mb500FeatureGroup.addLayer(L.polyline(latlngs, options));
                                        }
                                        latlngs = [];
                                        latlngs.push(latlng);
                                    } else {
                                        latlngs.push(latlng);
                                        if (i === len - 1) {
                                            if (self.ictmap.map.hasLayer(self.mb500FeatureGroup)) {
                                                self.mb500FeatureGroup.addLayer(L.polyline(latlngs, options));
                                            }
                                            latlngs = [];
                                        }
                                    }
                                }
                            }
                            // handler datq ----------------end-----------------------------
                            arr = [];
                        } else {
                            if (arr) {
                                arr.push(results.data[0]);
                            } else {
                                arr = [];
                            }
                        }
                    }
                });
            },

            remove500mb: function() {
                if (this.mb500FeatureGroup && this.ictmap.map.hasLayer(this.mb500FeatureGroup)) {
                    this.ictmap.map.removeLayer(this.mb500FeatureGroup);
                }
            },

            addWind: function(url) {
                var self = this;
                Papa.parse(url, {
                    download: true,
                    complete: function(results) {
                        var datas = results.data;
                        var config = {
                            lat: '0',
                            lng: '1',
                            dir: '3',
                            value: '2',
                            data: datas
                        };
                        self.removeWind();
                        self.windLayer = new L.WindLayer(null, config);
                        self.ictmap.map.addLayer(self.windLayer);
                    }
                });
            },

            removeWind: function() {
                if (this.windLayer && this.ictmap.map.hasLayer(this.windLayer)) {
                    this.ictmap.map.removeLayer(this.windLayer);
                }
            },

            addWave: function(url) {
                var self = this;
                var renderer = new L.TextCanvas();
                var options = {
                    renderer: renderer,
                    color: '#354656',
                    weight: 0.8,
                    opacity: 0.85,
                    fill: false
                };
                var arr = [];

                this.removeWave();
                this.waveFeatureGroup = L.featureGroup([]).addTo(this.ictmap.map);

                Papa.parse(url, {
                    download: true,
                    complete: function(results) {},
                    step: function(results, parser) {
                        if (results.data[0][0] === '' && arr.length) {

                            // handler data -------------start------------------------
                            var latlngs = [];
                            for (var i = 0, len = arr.length; i < len; i++) {
                                var row = arr[i];
                                var lat = +row[0];
                                var lng = +row[1];
                                var value = options.text = +row[2];
                                var latlng = L.latLng(lat, lng);

                                if (i === 0) {
                                    latlngs.push(latlng);
                                } else {
                                    var lastlng = (latlngs[latlngs.length - 1]).lng;
                                    var extend = Math.abs(lng - lastlng);
                                    if (extend >= 180) { //解决经度范围超过180连线异常
                                        if (self.ictmap.map.hasLayer(self.waveFeatureGroup)) {
                                            self.waveFeatureGroup.addLayer(L.polyline(latlngs, options));
                                        }
                                        latlngs = [];
                                        latlngs.push(latlng);
                                    } else {
                                        latlngs.push(latlng);
                                        if (i === len - 1) {
                                            if (self.ictmap.map.hasLayer(self.waveFeatureGroup)) {
                                                self.waveFeatureGroup.addLayer(L.polyline(latlngs, options));
                                            }
                                            latlngs = [];
                                        }
                                    }
                                }
                            }
                            // handler datq ----------------end-----------------------------
                            arr = [];
                        } else {
                            if (arr) {
                                arr.push(results.data[0]);
                            } else {
                                arr = [];
                            }
                        }
                    }
                });
            },

            removeWave: function() {
                if (this.waveFeatureGroup && this.ictmap.map.hasLayer(this.waveFeatureGroup)) {
                    this.ictmap.map.removeLayer(this.waveFeatureGroup);
                }
            },

            addSurge: function(url) {
                var self = this;
                Papa.parse(url, {
                    download: true,
                    complete: function(results) {
                        var datas = results.data;
                        var config = {
                            lat: '0',
                            lng: '1',
                            dir: '3',
                            value: '2',
                            data: datas
                        };
                        self.removeSurge();
                        self.surgeLayer = new L.FlowLayer(null, config);
                        self.ictmap.map.addLayer(self.surgeLayer);
                    }
                });
            },

            removeSurge: function() {
                if (this.surgeLayer && this.ictmap.map.hasLayer(this.surgeLayer)) {
                    this.ictmap.map.removeLayer(this.surgeLayer);
                }
            },

            addFlow: function(url) {
                var self = this;
                Papa.parse(url, {
                    download: true,
                    complete: function(results) {
                        var datas = results.data;
                        var config = {
                            lat: '0',
                            lng: '1',
                            dir: '3',
                            value: '2',
                            data: datas
                        };
                        self.removeFlow();
                        self.flowLayer = new L.FlowLayer(null, config);
                        self.ictmap.map.addLayer(self.flowLayer);
                    }
                });
            },

            removeFlow: function() {
                if (this.flowLayer && this.ictmap.map.hasLayer(this.flowLayer)) {
                    this.ictmap.map.removeLayer(this.flowLayer);
                }
            },

            addTemperature: function(url) {
                var self = this;
                var renderer = new L.TextCanvas();
                var options = {
                    renderer: renderer,
                    color: '#354656',
                    weight: 0.8,
                    opacity: 0.85,
                    fill: false
                };
                var arr = [];

                this.removeTemperature();
                this.tepFeatureGroup = L.featureGroup([]).addTo(this.ictmap.map);

                Papa.parse(url, {
                    download: true,
                    complete: function(results) {},
                    step: function(results, parser) {
                        if (results.data[0][0] === '' && arr.length) {

                            // handler data -------------start------------------------
                            var latlngs = [];
                            for (var i = 0, len = arr.length; i < len; i++) {
                                var row = arr[i];
                                var lat = +row[0];
                                var lng = +row[1];
                                var value = options.text = +row[2];
                                var latlng = L.latLng(lat, lng);

                                if (i === 0) {
                                    latlngs.push(latlng);
                                } else {
                                    var lastlng = (latlngs[latlngs.length - 1]).lng;
                                    var extend = Math.abs(lng - lastlng);
                                    if (extend >= 180) { //解决经度范围超过180连线异常
                                        if (self.ictmap.map.hasLayer(self.tepFeatureGroup)) {
                                            self.tepFeatureGroup.addLayer(L.polyline(latlngs, options));
                                        }
                                        latlngs = [];
                                        latlngs.push(latlng);
                                    } else {
                                        latlngs.push(latlng);
                                        if (i === len - 1) {
                                            if (self.ictmap.map.hasLayer(self.tepFeatureGroup)) {
                                                self.tepFeatureGroup.addLayer(L.polyline(latlngs, options));
                                            }
                                            latlngs = [];
                                        }
                                    }
                                }
                            }
                            // handler datq ----------------end-----------------------------
                            arr = [];
                        } else {
                            if (arr) {
                                arr.push(results.data[0]);
                            } else {
                                arr = [];
                            }
                        }
                    }
                });
            },

            removeTemperature: function() {
                if (this.tepFeatureGroup && this.ictmap.map.hasLayer(this.tepFeatureGroup)) {
                    this.ictmap.map.removeLayer(this.tepFeatureGroup);
                }
            },

            addVisibility: function(url) {
                var self = this;
                var renderer = new L.TextCanvas();
                var options = {
                    renderer: renderer,
                    color: '#000',
                    weight: 1,
                    fill: true,
                    fillColor: '#f00'
                };
                var arr = [];

                this.removeVisibility();
                this.visFeatureGroup = L.featureGroup([]).addTo(this.ictmap.map);

                Papa.parse(url, {
                    download: true,
                    complete: function(results) {},
                    step: function(results, parser) {
                        if (results.data[0][0] === '' && arr.length) {

                            // handler data -------------start------------------------
                            var latlngs = [];
                            for (var i = 0, len = arr.length; i < len; i++) {
                                var row = arr[i];
                                var lat = +row[0];
                                var lng = +row[1];
                                var value = options.text = +row[2];
                                var latlng = L.latLng(lat, lng);

                                if (i === 0) {
                                    latlngs.push(latlng);
                                } else {
                                    var lastlng = (latlngs[latlngs.length - 1]).lng;
                                    var extend = Math.abs(lng - lastlng);
                                    if (extend >= 180) { //解决经度范围超过180连线异常
                                        if (self.ictmap.map.hasLayer(self.visFeatureGroup)) {
                                            self.visFeatureGroup.addLayer(L.polygon(latlngs, options));
                                        }
                                        latlngs = [];
                                        latlngs.push(latlng);
                                    } else {
                                        latlngs.push(latlng);
                                        if (i === len - 1) {
                                            if (self.ictmap.map.hasLayer(self.visFeatureGroup)) {
                                                self.visFeatureGroup.addLayer(L.polygon(latlngs, options));
                                            }
                                            latlngs = [];
                                        }
                                    }
                                }
                            }
                            // handler datq ----------------end-----------------------------

                            arr = [];
                        } else {
                            if (arr) {
                                arr.push(results.data[0]);
                            } else {
                                arr = [];
                            }
                        }
                    }
                });
            },

            removeVisibility: function() {
                if (this.visFeatureGroup && this.ictmap.map.hasLayer(this.visFeatureGroup)) {
                    this.ictmap.map.removeLayer(this.visFeatureGroup);
                }
            }

        })
    });

});
